package com.leantech.android.browser.browser.web

import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.view.View
import android.webkit.PermissionRequest
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.cscj.android.utils.LOG


class RocketWebChromeClient(
    private val rocketWebView: RocketWebView
) : WebChromeClient() {

    companion object {
        private const val TAG = "RocketWebViewClient"
    }

    override fun onReceivedIcon(webView: WebView, icon: Bitmap?) {
        super.onReceivedIcon(webView, icon)
        LOG.d(TAG, "onReceivedIcon url ${webView.url} , icon $icon")
        val favicon = icon ?: return
        rocketWebView.webViewCallback?.onReceiveFavicon(webView.url, favicon)
    }

    override fun onProgressChanged(webView: WebView, progress: Int) {
        super.onProgressChanged(webView, progress)
        rocketWebView.webViewCallback?.onProgressUpdate(progress)
    }

    override fun onReceivedTitle(webView: WebView, title: String) {
        super.onReceivedTitle(webView, title)
        if (!title.startsWith("data:text")) {
            rocketWebView.webViewCallback?.onTitleUpdate(title)
        }
    }

    override fun onShowCustomView(view: View, callback: CustomViewCallback) {
        rocketWebView.webViewCallback?.onShowCustomView(view, callback)
    }

    override fun onHideCustomView() {
        super.onHideCustomView()
        rocketWebView.webViewCallback?.onHideCustomView()
    }

    override fun onShowFileChooser(
        webView: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams
    ): Boolean {
        rocketWebView.webViewCallback?.onShowFileChooser(callback, params)
        return true
    }

    private val posterBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
        .apply { setPixel(0, 0, Color.argb(0, 255, 255, 255)) }

    override fun getDefaultVideoPoster(): Bitmap = posterBitmap

    override fun onPermissionRequest(request: PermissionRequest) {
        super.onPermissionRequest(request)
        rocketWebView.webViewCallback?.onPermissionRequest(request)
    }
}